package com.borya.task.impl;

import java.util.*;

import com.borya.model.db.CitycodeRelate;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.borya.constant.RedisConstant;
import com.borya.dao.UploadSourceDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.framework.util.ObjectUtils;
import com.borya.model.entity.CardSource;
import com.borya.model.entity.PhoneSource;
import com.borya.model.entity.SelectInfo;
import com.borya.task.AbstractTaskService;
import com.borya.util.Constant;

@Component("resourceAutoTask")
public class ResourceAutoTask extends AbstractTaskService {
	
	private Logger log = Logger.getLogger(getClass());
	@Autowired("uploadSourceDAOImpl")
	private UploadSourceDAO sourceDAO;


	public ResourceAutoTask() {
		super(Constant.RESOURCE_AUTO_TASK);
	}

	@Override
	public void process(){
		try {
			final String  key = RedisConstant.REDIS_NAME_SPACE+"autoResourcetask";
			String isRunnung = sourceDAO.redis_get(key);
			if(ObjectUtils.isNullOrEmpty(isRunnung)){
				sourceDAO.redis_set(key,"1");
				sourceDAO.redis_expire(key,3600);
				log.info("号码自动入库");
				Map<String, String> smspMap = sourceDAO.saveSmsp();
				if(ObjectUtils.isNull(smspMap)){
					log.info("获取smsp列saveSmsp return null");
					return;
				}
				Map<String, String> phoneModelMap = sourceDAO.saveNumberRule();
				if(ObjectUtils.isNull(phoneModelMap)){
					log.info("获取资源模式sql return null");
					return;
				}
				Map<String, SelectInfo> selMap = sourceDAO.getLevelCode();
				if(selMap == null){
					log.error("getLevelCode return null");
					return;
				}
				Map<String, CitycodeRelate> cityMap = sourceDAO.allCityInfo();
				if(cityMap == null){
					log.error("allCityInfo return null");
					return;
				}
				boolean add = false;
				Set<String> alreadySource = new HashSet<>();
				List<PhoneSource> phoneList = sourceDAO.getPhoneResources(selMap);
				while(ObjectUtils.nonNullOrEmpty(phoneList)){
					add = true;
					alreadySource.clear();
					for(int i = 0,size = phoneList.size();i < size; i++){
						PhoneSource source = phoneList.get(i);
						/**如果一批队列中有重复号码，后面的号码不用修改**/
						if(alreadySource.contains(source.getPhone())){
							source.setMonopolyType(0);
						} else {
							alreadySource.add(source.getPhone());
						}
						dealPhoneSource(source, smspMap, phoneModelMap,cityMap);
					}
					boolean res = sourceDAO.insertAutoPhoneSource(phoneList);
					if(! res){
						log.info("号码自动入表失败");
						return;
					}
					phoneList = sourceDAO.getPhoneResources(selMap);
				}
				alreadySource.clear();
				if(add)
				{
					sourceDAO.updLog();
				}

				List<CardSource> cardList = sourceDAO.getCardResoutces();
				while(cardList != null && !cardList.isEmpty()){
					for(int i = 0,size = cardList.size();i < size; i++){
						CardSource source = cardList.get(i);
						/**如果一批队列中有重复号码，后面的号码是修改**/
						if(alreadySource.contains(source.getIccid())){
							source.setAid("1");
						} else {
							alreadySource.add(source.getIccid());
						}
						dealCardResource(source);
					}
					boolean res = sourceDAO.insertAutoCardSource(cardList);
					if(! res){
						log.info("卡自动入表失败");
						return;
					}
					cardList = sourceDAO.getCardResoutces();
				}
				alreadySource.clear();
				sourceDAO.redis_del(key);
			} else {
			    log.info("自动入库有任务进行中");
            }

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

	}
	
	private void dealPhoneSource(PhoneSource source, Map<String, String> smspMap
			, Map<String, String> modelMap,Map<String, CitycodeRelate> cityMap){
		source.setRightEight(source.getPhone().substring(3));
		source.setLeftThree(Integer.parseInt(source.getPhone().substring(0,3)));
		source.setProvinceCode(cityMap.get(source.getCityCode()).getProvinceCode());
		switch (source.getPhoneType()) {
		case 1:
			source.checkSourceYt();
			if(! source.isSourceTrue())
			{
				return;
			}
			setPretty(source);
			source.setCardMoneyCode("0");
			if(source.getService_type() == 1
					&& !ObjectUtils.isEqual("0",source.getCardMoney())){
				//大众号 无选号费的为0 有的为1
				source.setCardMoneyCode("1");
			}

			source.setSmsp(smspMap.get(source.getCityCode()));
			if(StringUtils.isBlank(source.getSmsp())){
				source.setSourceTrue(false);
				source.setDescStr("未获取到对应smsp");
			}
			source.setPhoneModelType("yuantel");
			source.setTfPhoneModelType("yuantel");
			break;
		case 2:
			source.checkSourceUnicom();
			if(! source.isSourceTrue())
			{
				return;
			}
			setPretty(source);
			source.setSmsp(smspMap.get(source.getCityCode()));
			if(StringUtils.isBlank(source.getSmsp())){
				source.setSourceTrue(false);
				source.setDescStr("未获取到对应smsp");
			}
			if(StringUtils.isNotBlank(source.getUnicomDealerId())
					&& modelMap.containsKey(source.getUnicomDealerId()))
			{
				source.setPhoneModelType(modelMap.get(source.getUnicomDealerId()));
			}
			else
			{
				source.setPhoneModelType(modelMap.get("basemodel"));
			}
			break;
		default:
			break;
		}
	}

	private void setPretty(PhoneSource source){
		if(! "0".equals(source.getBigNumberLevel())){
			source.setPretty(1);
			source.setRecommendation(1);
		}
		else{
			source.setPretty(2);
			source.setRecommendation(0);
		}
	}

	private void dealCardResource(CardSource source){
		source.checkCardInfo();
		if(! source.isSourceTrue())
			return;
		switch (source.getCardType()) {
		case 1:
			if(source.getIccid().length() != 20){
				source.setSourceTrue(false);
				source.setDescStr("卡资源错误:远特卡不为20位");
			}
			if(source.getCardResourceIdJN().length() == 0
					&& source.getCardResourceId().length() == 0){
				source.setSourceTrue(false);
				source.setDescStr("卡资源错误:远特卡无card_resource_id");
			}
			break;
		case 2:
			if(source.getIccid().length() != 19){
				source.setSourceTrue(false);
				source.setDescStr("卡资源错误:联通卡不为20位");
			}
			break;
		default:
			break;
		}
		source.setIccid19(source.getIccid().substring(0, 19));
	}
	
}
